package com.yswl.pri.home.vedio;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.tencent.smtt.export.external.interfaces.ClientCertRequest;
import com.tencent.smtt.export.external.interfaces.ConsoleMessage;
import com.tencent.smtt.export.external.interfaces.JsPromptResult;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.tencent.smtt.utils.TbsLog;
import com.yswl.pri.R;
import com.yswl.pri.common.ToolbarActivity;
import com.yswl.pri.home.vedio.utils.AnalysUtil;
import com.yswl.pri.home.vedio.utils.WebViewProgressBar;
import com.yswl.pri.home.vedio.utils.X5WebView;
import com.yswl.pri.home.Website;

import yswl.com.klibrary.util.L;

public class AnalysisActivity extends ToolbarActivity {
    public static void JumpAct(Context context, Website url) {
        Intent intent = new Intent(context, AnalysisActivity.class);
        intent.putExtra("url", url);
        context.startActivity(intent);
    }

    private static final String TAG = AnalysisActivity.class.getSimpleName();
    private ImageView mPlayer;
    public static FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, 6);
    public static FrameLayout.LayoutParams lp2 = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
    public static final String PC_USERAGENT = "Mozilla/5.0(Macintosh;IntelMacOSX10_7_0)AppleWebKit/535.11(KHTML,likeGecko)Chrome/17.0.963.56Safari/535.11";
    public static final String MOBULE_USERAGENT = "Mozilla/5.0 (Linux; Android 5.0; HUAWEI Build/tt) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/33.0.0.0 Mobile Safari/537.36";
    Website mWebSite;
    String mHomeUrl = "https://www.baidu.com";
    protected X5WebView mWebView;
    protected WebViewProgressBar mPageLoadingProgressBar = null;
    protected ViewGroup mViewParent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_analysis);
        mWebSite = (Website) getIntent().getSerializableExtra("url");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        initUI();
    }

    private void initUI() {
        mViewParent = findViewById(R.id.webView1);
        mWebView = new X5WebView(this, null);
        mPageLoadingProgressBar = new WebViewProgressBar(this);// new
        mViewParent.addView(mWebView, lp2);
        mViewParent.addView(mPageLoadingProgressBar, lp);

        mPlayer = findViewById(R.id.player);
        mPlayer.setVisibility(View.GONE);
        mPlayer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String url = (String) v.getTag();
                String title = AnalysisActivity.this.getTitle().toString();
                BrowserActivity.JumpAct(AnalysisActivity.this, title, url);

            }
        });

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                L.e(TAG, "[shouldOverrideUrlLoading] 2:" + url);
                if (TextUtils.isEmpty(url) || url.contains("about:blank")) return true;
                return false;
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest webResourceRequest) {
                L.e(TAG, "[shouldOverrideUrlLoading] 2:");
                return super.shouldOverrideUrlLoading(webView, webResourceRequest);
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView webView, String s) {
                L.e(TAG, "[shouldInterceptRequest] 1:" + s);
                return super.shouldInterceptRequest(webView, s);
            }

            @Override
            public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
                super.onPageStarted(webView, s, bitmap);
                L.e(TAG, "[onPageStarted] :" + s);
                L.e(TAG, "mPlayer set GONE");
                mPlayer.setVisibility(View.GONE);
                menuStatus = -1;
                invalidateOptionsMenu();
            }

            @Override
            public void onLoadResource(WebView webView, String url) {
                L.e(TAG, "[onLoadResource] : old url : " + url);
                String newUrl = AnalysUtil.analysUrlisOk(url, mWebSite.order);
                L.e(TAG, "[onLoadResource] :  new url :" + newUrl);
                if (!TextUtils.isEmpty(newUrl)) {
                    L.e(TAG, "mPlayer set VIS");
                    mPlayer.setVisibility(View.VISIBLE);
                    mPlayer.setTag(newUrl);
                }
                super.onLoadResource(webView, url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                L.e(TAG, "[onPageFinished] :" + url);
                String newUrl = AnalysUtil.analysUrlisOk(url, mWebSite.order);
                L.e(TAG, "[onLoadResource] :  new url :" + newUrl);
                if (!TextUtils.isEmpty(newUrl)) {
                    L.e(TAG, "mPlayer set VIS");
                    mPlayer.setVisibility(View.VISIBLE);
                    mPlayer.setTag(newUrl);
                }
                menuStatus = 0;
                invalidateOptionsMenu();
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView webView, WebResourceRequest webResourceRequest, Bundle bundle) {
                L.e(TAG, "[shouldInterceptRequest] ");
                return super.shouldInterceptRequest(webView, webResourceRequest, bundle);
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView webView, WebResourceRequest webResourceRequest) {
                L.e(TAG, "[shouldInterceptRequest] ");
                return super.shouldInterceptRequest(webView, webResourceRequest);
            }

            @Override
            public void onReceivedLoginRequest(WebView webView, String s, String s1, String s2) {
                L.e(TAG, "[onReceivedLoginRequest] ");
                super.onReceivedLoginRequest(webView, s, s1, s2);
            }

            @Override
            public void onDetectedBlankScreen(String s, int i) {
                L.e(TAG, "[onDetectedBlankScreen] ");
                super.onDetectedBlankScreen(s, i);
            }

            @Override
            public void onFormResubmission(WebView webView, Message message, Message message1) {
                L.e(TAG, "[onFormResubmission] ");
                super.onFormResubmission(webView, message, message1);
            }

            @Override
            public void onReceivedClientCertRequest(WebView webView, ClientCertRequest clientCertRequest) {
                L.e(TAG, "[onReceivedClientCertRequest] ");
                super.onReceivedClientCertRequest(webView, clientCertRequest);
            }

        });

        mWebView.setWebChromeClient(new WebChromeClient() {

            /**
             * webview setSupportMultipleWindows(true)对于
             *<a href="http://www.google.com" target="_blank">new window</a>
             * 起一个新窗口打开，而要截获这个请求  需在onCreateWindow
             *
             */
            @Override
            public boolean onCreateWindow(WebView webView, boolean isDialog, boolean isUserGesture, Message message) {
                final Context context;
                context = webView.getContext();
                android.webkit.WebView newWebView = new android.webkit.WebView(context);
                newWebView.setWebViewClient(new android.webkit.WebViewClient() {
                    @Override
                    public boolean shouldOverrideUrlLoading(android.webkit.WebView view, final String url) {
                        mWebSite.url = url;
                        AnalysisActivity.JumpAct(context, mWebSite);
                        return true;
                    }
                });
                android.webkit.WebView.WebViewTransport transport = (android.webkit.WebView.WebViewTransport) message.obj;
                transport.setWebView(newWebView);
                message.sendToTarget();
                L.e(TAG, "onCreateWindow " + message);
                return true;
            }

            @Override
            public void onProgressChanged(WebView webView, int newProgress) {
                super.onProgressChanged(webView, newProgress);
                if (null != mPageLoadingProgressBar) {
                    mPageLoadingProgressBar.setProgress(newProgress);
                }

            }

            @Override
            public void onReceivedTitle(WebView webView, String title) {
                CharSequence pnotfound = "The page cannot be found";
                L.e(TAG, "[onReceivedTitle]  title :" + title);
                if (TextUtils.isEmpty(title)) return;
                if (title.contains(pnotfound)) {
                    webView.stopLoading();
                } else {
                    String tit;
                    if (title.contains("-")) {
                        tit = title.split("-")[0];
                    } else if (title.contains("—")) {
                        tit = title.split("—")[0];
                    } else if (title.contains("_")) {
                        tit = title.split("_")[0];
                    } else {
                        tit = title;
                    }
                    L.e("TAG", "title :" + tit);
                    setTitle(tit);
                }
            }

            @Override
            public boolean onJsAlert(WebView webView, String s, String s1, JsResult jsResult) {
                jsResult.cancel();
                L.e(TAG, "[onJsAlert] --- url： " + webView.getUrl() + "\n---  s:" + s + "\n----  s1" + s1);
                return true;
            }

            @Override
            public boolean onJsBeforeUnload(WebView webView, String s, String s1, JsResult jsResult) {
                L.e(TAG, "[onJsBeforeUnload] --- url： " + webView.getUrl() + "\n---  s:" + s + "\n----  s1" + s1);
                return true;
            }


            @Override
            public void onReceivedTouchIconUrl(WebView webView, String s, boolean b) {
                L.e(TAG, "[onReceivedTouchIconUrl]");
                super.onReceivedTouchIconUrl(webView, s, b);
            }

            @Override
            public void onCloseWindow(WebView webView) {
                L.e(TAG, "[onCloseWindow]");
                super.onCloseWindow(webView);
            }

            @Override
            public boolean onJsTimeout() {
                L.e(TAG, "[onCloseWindow]");
                return super.onJsTimeout();
            }

            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                L.e(TAG, "[onConsoleMessage]");
                return true;
            }

            @Override
            public boolean onJsPrompt(WebView webView, String s, String s1, String s2, JsPromptResult jsPromptResult) {
                L.e(TAG, "[onJsPrompt]");
                return true;
            }

            @Override
            public boolean onJsConfirm(WebView webView, String s, String s1, JsResult jsResult) {
                L.e(TAG, "[onJsConfirm]");
                return true;
            }

            @Override
            public void onRequestFocus(WebView webView) {
                L.e(TAG, "[onRequestFocus]");
                super.onRequestFocus(webView);
            }
        });

        WebSettings webSetting = mWebView.getSettings();
        webSetting.setUserAgentString(PC_USERAGENT);
        long time = System.currentTimeMillis();
        if (mWebSite == null) {
            mWebView.loadUrl(mHomeUrl);
        } else {
            mWebView.loadUrl(mWebSite.url);
        }
        TbsLog.d("time-cost", "cost time: " + (System.currentTimeMillis() - time));
    }

    int menuStatus = -1;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (menuStatus == -1) {
            menu.add(0, 1, 0, "stop")
                    .setIcon(R.mipmap.icon_close).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        } else {
            menu.add(0, 1, 1, "刷新")
                    .setIcon(R.mipmap.icon_change).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        }


        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == 1) {
            if (item.getOrder() == 0) {
                mWebView.pauseTimers();
                mWebView.onPause();
                mWebView.stopLoading();
                invalidateOptionsMenu();

            } else {
                mWebView.reload();
            }
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        L.e(TAG, "[onNewIntent]");
        if (intent == null || mWebView == null || intent.getData() == null)
            return;
        mWebView.loadUrl(intent.getData().toString());
    }

    @Override
    protected void onResume() {
        L.e(TAG, "[onResume]");
        super.onResume();
        mWebView.onResume();
    }

    @Override
    protected void onPause() {
        L.e(TAG, "[onPause]");
        super.onPause();
        mWebView.onPause();
    }

    @Override
    protected void onDestroy() {
        L.e(TAG, "[onDestroy]");
        if (mWebView != null) {
            mWebView.clearView();
            mWebView.destroy();
        }
        mWebView = null;
        mViewParent.removeAllViews();
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        L.e(TAG, "[onBackPressed]");
        if (mWebView != null && mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        L.e(TAG, "[onKeyDown]");

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mWebView != null && mWebView.canGoBack()) {
                mWebView.goBack();
                return true;
            } else
                return super.onKeyDown(keyCode, event);
        }
        return super.onKeyDown(keyCode, event);
    }

}
